package com.apestech.framework.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Clob;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.druid.sql.visitor.functions.Char;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.pinyin.Converter;
import com.apestech.framework.pinyin.PinyinConverter;
import com.apestech.framework.util.callback.SpiltStrCallback;
import com.apestech.framework.util.callback.SpiltStrCallbackReturn;

/**
 * 字串二次处理,公式执行工具函数合集
 * @author hupo
 *
 */
public class StringUtil extends MessageUtil{
	
	public static TimeZone         defaultTimeZone      = TimeZone.getDefault();
    public static Locale           defaultLocale        = Locale.getDefault();
    public static String           DEFAULT_TYPE_KEY     = "@type";
    public static String           DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static int              DEFAULT_PARSER_FEATURE;
	
	/*字串处理*/
    
    /**
     * 获取16位随机UUID码
     * @return
     */
    public static String getUUID(){
    	return UUID.randomUUID().toString().replaceAll("-", "");
    }

	public static String getRandomString(int length){
		//默认长度16
		if(length == 0){length = 16;}
		//定义一个字符串（A-Z，a-z，0-9）即62位；
		String str="zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
		//由Random生成随机数
		Random random=new Random();
		StringBuffer sb=new StringBuffer();
		//长度为几就循环几次
		for(int i=0; i<length; ++i){
			//产生0-61的数字
			int number=random.nextInt(62);
			//将产生的数字通过length次承载到sb中
			sb.append(str.charAt(number));
		}
		//将承载的字符转换成字符串
		return sb.toString();
	}

	/**
	 * 判断字串是否为正整数
	 * @param string
	 * @return
	 */
	public static boolean isPureDigital(String string) {
		if (isBlank(string))
			return false;
		String regEx1 = "\\d+";
		Pattern p;
		Matcher m;
		p = Pattern.compile(regEx1);
		m = p.matcher(string);
		if (m.matches())
			return true;
		else
			return false;
	}

	public static void execSplitStr(String text, String split, SpiltStrCallback spiltStrCallback) throws Exception {
		if(text==null) return;
		text=text.trim();
		if("".equals(text)) return;
		int pos=text.indexOf(split);
		if(pos>=0){
			String[] list=text.split(split);
			int len=list.length;
			for(int i=0; i<len; i++){
				String txt=list[i].trim();
				if(!"".equals(txt)) spiltStrCallback.exec(txt);
			}
		} else {
			spiltStrCallback.exec(text);
		}
	}

	public static boolean execSplitStr(String text, String split, SpiltStrCallbackReturn spiltStrCallback) throws Exception {
		if(text==null) return false;
		text=text.trim();
		if("".equals(text)) return false;
		int pos=text.indexOf(split);
		if(pos>=0){
			String[] list=text.split(split);
			int len=list.length;
			for(int i=0; i<len; i++){
				String txt=list[i].trim();
				if(!"".equals(txt)){
					if(!spiltStrCallback.exec(txt)) return false;
				}
			}
		} else {
			if(!spiltStrCallback.exec(text)) return false;
		}
		return true;
	}

    public static String getSubStr(String source, String target, String delimiter, boolean in){
    	String sour=delimiter+source+delimiter;
    	String str="";
    	target=target+delimiter;
    	String[] list=target.split(delimiter);
    	int len=list.length;
    	for(int i=0; i<len; i++){
    		String s=list[i];
    		if(s!=null){
    			if((sour).indexOf(delimiter+s+delimiter)>=0){
    				if(in){
    					if(!"".equals(str)){
    						str=str+delimiter;
						}
    					str=str+s;
					} else {
    					if("".equals(str)){
							str=sour;
						}
    					str=str.replace(delimiter+s+delimiter, delimiter);
    					if(!leftStr(str,1).equals(delimiter)){
							str=delimiter+str;
						}
					}
				}
			}
		}
		if(!in){
    		if(str.length()>2){
				str=str.substring(1, str.length()-1);
			}
		}
		return str;
	}


	
    /**
     * 获取文件目录中的文件名子串
     * @param filename
     * @return
     */
    public String getFileString(String filename){
		filename = filename.trim();
		if(filename.indexOf(".")<0) return "";
		String d="/";
		if(filename.indexOf("/")<0){
			d="\\";
		}
		return filename.substring(filename.lastIndexOf(d)+d.length());	
	}
	
    /**
     * 获取文件目录中的目录子串
     * @param filename
     * @return
     */
	public String getDirString(String filename){
		filename = filename.trim();
		String file="";
		String s=rightStr(filename, 1);
		String d="/";
		if(filename.indexOf("/")<0){
			d="\\";
		}
		if(s.equals(d)){
			return filename;
		}
		if(filename.indexOf(".")<0){
			if(!s.equals(d)){
				filename=filename+d;
			}
			return filename;
		}
		return filename.substring(0,filename.lastIndexOf(d)+d.length());
	}
    
	/**
	 * 格式化函字串函数,在对应长度前补0,调用示例: 传入"A01" 要求总长度为6位, 输出"000A01"
	 * @param text String 处理字串 String 处理字串
	 * @param length  int 输出字串长度
	 * @return
	 */
	public static String prefixStr0(String text, int length) {
		StringBuilder str= new StringBuilder();
		return prefixStr(text, "0", length); 
	}
	
	/**
	 * 根据配置长度对传入字串前后补齐前缀字符
	 * @param text   String 处理字串
	 * @param prefix String 前缀字符
	 * @param length int    长度
	 * @return
	 */
	public static String prefixStr(String text, String prefix, int length) {
		if(text==null){
			return null;
		}
		if(text.length()>length){
			return text;
		}
		int ilen = text.length();  
		while(ilen < length) {  
			text = prefix + text;  
			ilen++;  
		}  
		return text;  
	}
	
	/**
	 * 根据配置长度对传入字串后补齐后缀字符
	 * @param text    String 处理字串
	 * @param postfix String 后缀字符
	 * @param length  int    长度
	 * @return
	 */
	public static String postfixStr(String text, String postfix, int length) {
		if(text==null){
			return null;
		}
		if(text.length()>length){
			return text;
		}
		int ilen = text.length();  
		while(ilen < length) {  
			text = text+postfix;  
			ilen++;  
		}  
		return text;  
	}

	/**
	 * 取左串
	 * @param text String 处理字串
	 * @param length  int 子串长度
	 * @return
	 */
	public static String leftStr(String text, int length) {
		if(text.length()<=length){
			return text;
		}
		return text.substring(0, length);
	}

	/**
	 * 取右串
	 * @param text String 处理字串
	 * @param length  int 子串长度
	 * @return
	 */
	public static String rightStr(String text, int length) {
		if(text.length()<=length){
			return text;
		}
		return text.substring(text.length() - length, text.length());
	}
	
	/**
	 * 序列化一-二级分割符字串为列表方式,可用于二次数据处理加工使用,字串格式示例:  "0:金额;1:比率;2:文本;3:列表"
	 * @param split String 分割符字串,存在多种用空格分割 示例:": ;"
	 * @param value String 要处理的字串
	 * @return
	 */
	public static ArrayList<ArrayList<String>> getStrSplitList(String split, String value){
		return getStrSplitList(split, value, null, null, true);
	}
	
	/**
	 * 序列化一-二级分割符字串为列表方式,可用于二次数据处理加工使用,字串格式示例:  "0:金额;1:比率;2:文本;3:列表"
	 * @param split String 分割符字串,存在多种用空格分割 示例:": ;"
	 * @param value String 要处理的字串
	 * @param resultList ArrayList<ArrayList<String>> 初始调用值为null, 强制写法
	 * @param detailList ArrayList<String> 初始调用值为null, 强制写法
	 * @param bFirst boolean 初始调用值为true, 强制写法
	 * @return
	 */
	private static ArrayList<ArrayList<String>> getStrSplitList(String split, String value, ArrayList<ArrayList<String>> resultList, ArrayList<String> detailList, boolean bFirst){
		if(detailList==null){
			detailList=new ArrayList<String>();
		}
		if(resultList==null){
			resultList=new ArrayList<ArrayList<String>>();
		}
		String [] splist=split.split(" ");
		String sSplit=splist[0].trim();
		int splen=splist.length;
		if(!"".equals(sSplit)){
			String[] list=value.split(sSplit);
			int ilen=list.length;
			for(int i=0;i<ilen;i++){
				if(splen==1 && ilen==1){
					detailList.add(list[i]);
				} else {
					String nSplit=split.replace(sSplit+" ", "");
					getStrSplitList(nSplit, list[i], resultList, detailList, false);
				}
				if(bFirst){
					resultList.add(detailList);
					detailList=new ArrayList<String>();
				}
			}
		}
		return resultList;
	}
	
	/**
	 * 获取字串中格式为#{}类型的变量列表，即与iBatis, myBatis风格一致变量类型
	 * @param text String 处理字串
	 * @return
	 */
	public static ArrayList<String> getBatisVariableList(String text){
		return getKeyList(text, "#{", "}", false);
	}
	
	/**
	 * 获取字串中格式为#{}类型的变量列表，即与iBatis, myBatis风格一致变量类型
	 * @param text String 处理字串
	 * @param all boolean 是否显示全部字段
	 * @return
	 */
	public static ArrayList<String> getBatisVariableList(String text, boolean all){
		return getKeyList(text, "#{", "}", all);
	}
	
	/**
	 * 替换#{}参数里的值,带入值可为任何类型
	 * @param text String 处理字串
	 * @param key  String 
	 * @param value Object
	 * @return
	 */
	public static String replaceBatisVariable(String text, String key, Object value){
		return replaceVariable(text, key, value, "#\\{", "\\}");
	}
	
	/**
	 * 是否存在#{}类型的参数
	 * @param text String 处理字串
	 * @return
	 */
	public static boolean hasBatisVariable(String text){
		return hasVariable(text, "#{", "}");
	}
	
	/**
	 * 获取字串中以前后缀方式对应的变量列表,示例 "#{变量}"
	 * @param text String 处理字串 处理字串
	 * @param prefix String 前缀字串 "#{"
	 * @param postfix String 后缀字串 "}"
	 * @return
	 */
	public static ArrayList<String> getKeyList(String text, String prefix, String postfix, boolean all){
		if(text==null){
			return null;
		}
		String stext=text;
		ArrayList<String> list=new ArrayList<String>();
		String sText=text;
		int ist=sText.indexOf(prefix);
		int ien=sText.indexOf(postfix, ist);
		if(ist<0 && ien<0){
			return null;
		}
		String sStr="";
		while(ist>=0 && ien>=0){
			String str=sText.substring(ist+2, ien);
			sText=sText.substring(ien+1, sText.length());
			ist=sText.indexOf(prefix);
			ien=sText.indexOf(postfix);
			if((";"+sStr+";").indexOf(str)<0 || all){
				list.add(str);
				sStr=sStr+";"+str+";";
				stext=stext.replace(prefix+str+postfix, "?");
			}
		}
		if(all){
			list.add(stext);
		}
		return list;
	}
	
	/**
	 * 替换变量,前后缀字串需要自行传入
	 * @param text String 处理字串
	 * @param key String
	 * @param value Object
	 * @param prefix String 前缀字串
	 * @param postfix String 后缀字串,注意如果涉及关键字类型字符(如: { } ")前面需要补\\
	 * @return
	 */
	public static String replaceVariable(String text, String key, Object value, String prefix, String postfix){
		String val="";
		if(value!=null){
			val=value.toString();
		}
		return text.replaceAll(prefix+key+postfix, val);
	}
	
	/**
	 * 是否存在自定义类型的参数,前后缀字串需要自行传入
	 * @param text String 处理字串
	 * @param prefix String 前缀字串
	 * @param postfix String 后缀字串
	 * @return
	 */
	public static boolean hasVariable(String text, String prefix, String postfix){
		if(text==null){
			return false;
		} else {
			if(text.indexOf(prefix)>=0 || text.indexOf(postfix)>=0){
				return true;
			} else {
				return false;
			}
		}
	}
	
	/**
	 * 特殊字符处理,主要处理对象是全角字符调成半角字符
	 * @param text String 处理字串
	 * @return
	 */
	public static String specialCharacter(String text){
		if(text==null) return "";
		text=text.replace("（", "\\(");
		text=text.replace("）", "\\)");
		text=text.replace("，", ";");
		text=text.replace(",", ";");
		text=text.replace("：", ":");
		text=text.replace("；", ";");
		text=text.replace(" ", "");
		text=text.replace("\\", "");
		return text;
	}

	public static JSONObject getStrSplitValueJson(String split, String value) throws Exception {
        value=specialCharacter(value);
		ArrayList<ArrayList<String>> list=getStrSplitList("; :", value);
        JSONObject map=new JSONObject();
        int len=list.size();
        if(len<2) return null;
        for(int i=0; i<len; i++){
            ArrayList<String> item=list.get(i);
            map.put(item.get(1), item.get(0));
        }
        return map;
	}

	/**
	 * 处理"ID(内容)"格式中非法字符,数据有效性检查
	 * @param id String
	 * @return
	 * @throws Exception
	 */
	public static String formatIdMemo(String id) throws Exception{
		id=specialCharacter(id);
		if(id.indexOf("(")>=0 && id.indexOf(")")<0){
			throw new Exception(getMessage("string_formatIdMemo","请检查:【 ({0}) 】内容缺少 【 ({1}) 】!",id));
		}
		return id;
	}
	
	/**
	 * 获取"ID(内容)"中ID部分的值
	 * @param id String
	 * @return
	 * @throws Exception
	 */
	public static String getSpiltId(String id) throws Exception{
		id=formatIdMemo(id);
		if(id.indexOf("(")>=0){
			id=id.substring(0, id.indexOf("("));
		}
		return id;
	}

	/**
	 * 获取"ID(内容)"中内容部分的值
	 * @param id String
	 * @return
	 * @throws Exception
	 */
	public static String getSplitList(String id) throws Exception{
		id=formatIdMemo(id);
		if(id.indexOf("(")>=0){
			id=id.substring(id.indexOf("(")+1, id.indexOf(")"));
		} else {
			return "";
		}
		return id;
	}
	
	/**
	 * 带入值如为null,返回空串,不为空,将值返回为字串
	 * @param value Object
	 * @return
	 */
	public static String getString(Object value){
		if(value==null){
			return "";
		}
		return value.toString();
	}
	
	/**
	 * 字符在字符串中出现的次数
	 * 
	 * @param text
	 * @param keyword
	 * @return
	 */
	public static int countString(String text, String keyword) {
		int pos = -2;
		int n = 0;

		while (pos != -1) {
			if (pos == -2) {
				pos = -1;
			}
			pos = text.indexOf(keyword, pos + 1);
			if (pos != -1) {
				n++;
			}
		}
		return n;
	}
	
	/**
	 * 获取某个子串在文本中存在的最后位置
	 * @param text
	 * @param keyword
	 * @return
	 */
	public static int getLastPos(String text, String keyword) {
		String sub=text;
		int pos=sub.indexOf(keyword);
        int lastpos=0;
        int ipos=-1;
        while (pos>=0) {
        	int length=sub.length();
        	sub=sub.substring(sub.indexOf(keyword)+keyword.length(), length);
        	ipos=pos+lastpos;
        	lastpos=lastpos+pos+keyword.length();
        	pos=sub.indexOf(keyword);
        }
        return ipos;
	}
	
	/**
	 * 将含有()的部分拆分出来
	 * @param text
	 * @return
	 * @throws Exception
	 */
	public static ArrayList<String> getBracket(String text) throws Exception{
		ArrayList<String> list=new ArrayList<String>();
		String sub=text;
		int start=-1;
		int end=-1;
		start=sub.indexOf("(");
		end=sub.indexOf(")");
		boolean error=false;
		if(start<0){
			list.add(text);
		} else {
			while(sub.length()>0){
				String str=sub;
				if(start>=0){
					if(start>end){
						error=true;
						break;
					}
					str=sub.substring(start, end+1);
				}
				int st=countString(str, "(");
				int en=countString(str, ")");
				while(st!=en){
					end=sub.indexOf(")", end+1);
					if(end<0){
						error=true;
						break;
					}
					str=sub.substring(start, end+1);
					st=countString(str, "(");
					en=countString(str, ")");
					if(end==sub.length()-1){
						break;
					}
				}
				if(st==en){  //找到
					if(end<0){  //不存在()
						list.add(str);
						sub="";
					} else {
						list.add(sub.substring(0, start));
						list.add(str);
						sub=sub.substring(end+1, sub.length());
						start=sub.indexOf("(");
						end=sub.indexOf(")");
					}
				} else {
					error=true;
					break;
				}
			}
		}
		
		if(error){
			int st=countString(text, "(");
			int en=countString(text, ")");
			throw new Exception(getMessage("StringFuncUtil_errorBracket","括号个数不同:([({0})]和)[({1})]对应数量必须相同!", st, en));
		}
		return list;
	}
	
	/**
     * 将String[]变量里的内容，按照字符[忽略大小写]排序，排序方式是：ASCII字符的正序进行排序
     * @param list
     * @return
     */
    public static String[] getOrderList(String[] list){
    	Vector v = new Vector();   
    	int len=list.length;
        for (int i = 0; i < len; i++) {   
            v.add(list[i]);   
        }   
        java.util.Collections.sort(v, String.CASE_INSENSITIVE_ORDER);   
        v.copyInto(list);   
        v = null;   
        return list;
    }

	public static String setSeparator(String s1, String separator, boolean first, boolean last){
		String sep=separator.toLowerCase();
		if("and".equals(sep) || "or".equals(sep)){
			if(!first){
				s1=separator+" "+s1;
			}
		} else {
			if(!last){
				s1=s1+separator;
			}
		}
		return s1;
	}

	public static int countChinese(String text) {
		String Reg="^[\u4e00-\u9fa5]{1}$";//正则
		int result=0;
		for(int i=0;i<text.length();i++){
			String b=Character.toString(text.charAt(i));
			if(b.matches(Reg))result++;
		}
		return result;
	}
	
	/*字串处理*/
	
	/*类型转换*/
	/**
	 * 与JSONObject类型转义有关的函数合�?
	 */
	public static Boolean castToBoolean(Object value) throws Exception{
        if(value == null){
            return null;
        }
        if(value instanceof Boolean){
            return (Boolean) value;
        }
        if(value instanceof Number){
            return ((Number) value).intValue() == 1;
        }
        if(value instanceof String){
            String strVal = (String) value;
            if(strVal.length() == 0 //
                    || "null".equals(strVal) //
                    || "NULL".equals(strVal)){
                return null;
            }
            if("true".equalsIgnoreCase(strVal) //
                    || "1".equals(strVal)){
                return Boolean.TRUE;
            }
            if("false".equalsIgnoreCase(strVal) //
                    || "0".equals(strVal)){
                return Boolean.FALSE;
            }
            if("Y".equalsIgnoreCase(strVal) //
                    || "T".equals(strVal)){
                return Boolean.TRUE;
            }
            if("F".equalsIgnoreCase(strVal) //
                    || "N".equals(strVal)){
                return Boolean.FALSE;
            }
        }
        throw new Exception(getMessage("string_caseBoolean","【 ({0}) 】不能转换成boolean类型！ ", value));
    }
	
	public static byte[] castToBytes(Object value) throws Exception{
		if(value == null){
            return null;
        }
        if(value instanceof byte[]){
            return (byte[]) value;
        }
        if(value instanceof String){
            return IOUtil.decodeBase64((String) value);
        }
        throw new Exception(getMessage("string_caseInt","【 ({0}) 】不能转换成int类型！ ", value));
    }
	
	public static Byte castToByte(Object value) throws Exception{
        if(value == null){
            return null;
        }
        if(value instanceof Number){
            return ((Number) value).byteValue();
        }
        if(value instanceof String){
            String strVal = (String) value;
            if(strVal.length() == 0 //
                    || "null".equals(strVal) //
                    || "NULL".equals(strVal)){
                return null;
            }
            return Byte.parseByte(strVal);
        }
        throw new Exception(getMessage("string_caseByte","【 ({0}) 】不能转换成byte类型！ ", value));
    }
	
	public static Short castToShort(Object value) throws Exception{
        if(value == null){
            return null;
        }
        if(value instanceof Number){
            return ((Number) value).shortValue();
        }
        if(value instanceof String){
            String strVal = (String) value;
            if(strVal.length() == 0 //
                    || "null".equals(strVal) //
                    || "NULL".equals(strVal)){
                return null;
            }
            return Short.parseShort(strVal);
        }
        throw new Exception(getMessage("string_caseShort","【 ({0}) 】不能转换成short类型！ ", value));
    }
	
	public static Integer castToInt(Object value) throws Exception{
        if(value == null){
            return null;
        }
        if(value instanceof Integer){
            return (Integer) value;
        }
        if(value instanceof Number){
            return ((Number) value).intValue();
        }
        if(value instanceof String){
            String strVal = (String) value;
            if(strVal.length() == 0 //
                    || "null".equals(strVal) //
                    || "NULL".equals(strVal)){
                return null;
            }
            if(strVal.indexOf(',') != 0){
                strVal = strVal.replaceAll(",", "");
            }
            return Integer.parseInt(strVal);
        }
        if(value instanceof Boolean){
            return ((Boolean) value).booleanValue() ? 1 : 0;
        }
        if(value instanceof Map){
            Map map = (Map) value;
            if(map.size() == 2
                    && map.containsKey("andIncrement")
                    && map.containsKey("andDecrement")){
                Iterator iter = map.values().iterator();
                iter.next();
                Object value2 = iter.next();
                return castToInt(value2);
            }
        }
        throw new Exception(getMessage("string_caseInt","【 ({0}) 】不能转换成int类型！ ", value));
    }
	
	public static Long castToLong(Object value) throws Exception{
        if(value == null){
            return null;
        }
        if(value instanceof Number){
            return ((Number) value).longValue();
        }
        if(value instanceof String){
            String strVal = (String) value;
            if(strVal.length() == 0 //
                    || "null".equals(strVal) //
                    || "NULL".equals(strVal)){
                return null;
            }
            if(strVal.indexOf(',') != 0){
                strVal = strVal.replaceAll(",", "");
            }
            try{
                return Long.parseLong(strVal);
            } catch(NumberFormatException ex){
                //
            }
        }
        if(value instanceof Map){
            Map map = (Map) value;
            if(map.size() == 2
                    && map.containsKey("andIncrement")
                    && map.containsKey("andDecrement")){
                Iterator iter = map.values().iterator();
                iter.next();
                Object value2 = iter.next();
                return castToLong(value2);
            }
        }
        throw new Exception(getMessage("string_caseLong","【 ({0}) 】不能转换成long类型！ ", value));
    }
	
	public static Float castToFloat(Object value) throws Exception{
        if(value == null){
            return null;
        }
        if(value instanceof Number){
            return ((Number) value).floatValue();
        }
        if(value instanceof String){
            String strVal = value.toString();
            if(strVal.length() == 0 //
                    || "null".equals(strVal) //
                    || "NULL".equals(strVal)){
                return null;
            }
            if(strVal.indexOf(',') != 0){
                strVal = strVal.replaceAll(",", "");
            }
            return Float.parseFloat(strVal);
        }
        throw new Exception(getMessage("string_caseFloat","【 ({0}) 】不能转换成float类型！ ", value));
    }
	
	public static Double castToDouble(Object value) throws Exception{
        if(value == null){
            return null;
        }
        if(value instanceof Number){
            return ((Number) value).doubleValue();
        }
        if(value instanceof String){
            String strVal = value.toString();
            if(strVal.length() == 0 //
                    || "null".equals(strVal) //
                    || "NULL".equals(strVal)){
                return null;
            }
            if(strVal.indexOf(',') != 0){
                strVal = strVal.replaceAll(",", "");
            }
            return Double.parseDouble(strVal);
        }
        throw new Exception(getMessage("string_caseDouble","【 ({0}) 】不能转换成double类型！ ", value));
    }
	
	public static BigDecimal castToBigDecimal(Object value){
        if(value == null){
            return null;
        }
        if(value instanceof BigDecimal){
            return (BigDecimal) value;
        }
        if(value instanceof BigInteger){
            return new BigDecimal((BigInteger) value);
        }
        String strVal = value.toString();
        if(strVal.length() == 0){
            return null;
        }
        if(value instanceof Map && ((Map) value).size() == 0){
            return null;
        }
        return new BigDecimal(strVal);
    }
	
	public static BigInteger castToBigInteger(Object value){
        if(value == null){
            return null;
        }
        if(value instanceof BigInteger){
            return (BigInteger) value;
        }
        if(value instanceof Float || value instanceof Double){
            return BigInteger.valueOf(((Number) value).longValue());
        }
        String strVal = value.toString();
        if(strVal.length() == 0 //
                || "null".equals(strVal) //
                || "NULL".equals(strVal)){
            return null;
        }
        return new BigInteger(strVal);
    }
	
	public static Date castToDate(Object value) throws Exception{
		if("SYSDATE".equals(value)){
			return new Date();
		}
        if(value == null){
            return null;
        }
        if(value instanceof Date){ // 使用频率�?��的，应优先处�?
            return (Date) value;
        }
        if(value instanceof Calendar){
            return ((Calendar) value).getTime();
        }
        long longValue = -1;
        if(value instanceof Number){
            longValue = ((Number) value).longValue();
            return new Date(longValue);
        }
        if(value instanceof String){
            String strVal = (String) value;
            if(strVal.startsWith("/Date(") && strVal.endsWith(")/")){
                String dotnetDateStr = strVal.substring(6, strVal.length() - 2);
                strVal = dotnetDateStr;
            }
            if(strVal.indexOf('-') != -1){
                String format;
                if(strVal.length() == DEFFAULT_DATE_FORMAT.length()){
                    format = DEFFAULT_DATE_FORMAT;
                } else if(strVal.length() == 10){
                    format = "yyyy-MM-dd";
                } else if(strVal.length() == "yyyy-MM-dd HH:mm:ss".length()){
                    format = "yyyy-MM-dd HH:mm:ss";
                } else if(strVal.length() == 29
                        && strVal.charAt(26) == ':'
                        && strVal.charAt(28) == '0'){
                    format = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
                } else{
                    format = "yyyy-MM-dd HH:mm:ss.SSS";
                }
                SimpleDateFormat dateFormat = new SimpleDateFormat(format, defaultLocale);
                dateFormat.setTimeZone(defaultTimeZone);
                try{
                    return (Date) dateFormat.parse(strVal);
                } catch(ParseException e){
                	throw new Exception(getMessage("string_caseDate","【 ({0}) 】不能转换成Date类型！ ", strVal)); // TODO 忽略 1970-01-01 之前的时间处理？
                }
            }
            if(strVal.length() == 0){
                return null;
            }
            longValue = Long.parseLong(strVal);
        }
        return new Date(longValue);
    }
	
	public static boolean isNumber(String str){
		// 该正则表达式可以匹配所有的数字 包括负数
		Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
		String bigStr;
		try {
			bigStr = new BigDecimal(str).toString();
		} catch (Exception e) {
			return false;//异常 说明包含非数字。
		}

		Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配
		if (!isNum.matches()) {
			return false;
		}
		return true;
    }
	
	public static java.sql.Date castToSqlDate(Object value) throws Exception{
        if(value == null){
            return null;
        }
        if(value instanceof java.sql.Date){
            return (java.sql.Date) value;
        }
        if(value instanceof Date){
            return new java.sql.Date(((Date) value).getTime());
        }
        if(value instanceof Calendar){
            return new java.sql.Date(((Calendar) value).getTimeInMillis());
        }
        long longValue = 0;
        if(value instanceof Number){
            longValue = ((Number) value).longValue();
        }
        if(value instanceof String){
            String strVal = (String) value;
            if(strVal.length() == 0 //
                    || "null".equals(strVal) //
                    || "NULL".equals(strVal)){
                return null;
            }
            if(isNumber(strVal)){
                longValue = Long.parseLong(strVal);
            } 
        }
        if(longValue <= 0){
        	throw new Exception(getMessage("string_caseDate","【 ({0}) 】不能转换成Date类型！ ", value)); // TODO 忽略 1970-01-01 之前的时间处理？
        }
        return new java.sql.Date(longValue);
    }
	
	public static java.sql.Timestamp castToTimestamp(Object value) throws Exception{
        if(value == null){
            return null;
        }
        if(value instanceof Calendar){
            return new java.sql.Timestamp(((Calendar) value).getTimeInMillis());
        }
        if(value instanceof java.sql.Timestamp){
            return (java.sql.Timestamp) value;
        }
        if(value instanceof Date){
            return new java.sql.Timestamp(((Date) value).getTime());
        }
        long longValue = 0;
        if(value instanceof Number){
            longValue = ((Number) value).longValue();
        }
        if(value instanceof String){
            String strVal = (String) value;
            if(strVal.length() == 0 //
                    || "null".equals(strVal) //
                    || "NULL".equals(strVal)){
                return null;
            }
            if(strVal.endsWith(".000000000")){
                strVal = strVal.substring(0, strVal.length() - 10);
            } else if(strVal.endsWith(".000000")){
                strVal = strVal.substring(0, strVal.length() - 7);
            }
            if(isNumber(strVal)){
                longValue = Long.parseLong(strVal);
            }
        }
        if(longValue <= 0){
        	throw new Exception(getMessage("string_caseTimestamp","【 ({0}) 】不能转换成Timestamp类型！ ", value));
        }
        return new java.sql.Timestamp(longValue);
    }
	
	public static String castToString(Object value){
        if(value == null){
            return null;
        }
        return value.toString();
    }

	public static String castNumberToString(Object value, int iscale){
		if(value == null){
			return null;
		}
		String s=value.toString();
		int dpos=s.indexOf(".");
		if("0".equals(leftStr(s,1)) && dpos<0) return null;
		if(isNumber(s)){
			int pos=s.indexOf(".");
			if(s.indexOf(".")>0){
				int len=s.substring(pos, s.length()).length();
				if(len<iscale){
					for(int i=0; i<iscale-len; i++){
						s=s+"0";
					}
				}
			} else {
				s=s+".";
				for(int i=0; i<iscale; i++){
					s=s+"0";
				}
			}
		} else{
			s=null;
		}
		return s;
	}

    public static String castClobToString(Clob value) throws Exception {
		String reString = "";
		Reader is = value.getCharacterStream();// 得到流
		BufferedReader br = new BufferedReader(is);
		String s = br.readLine();
		StringBuffer sb = new StringBuffer();
		while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
			sb.append(s);
			s = br.readLine();
		}
		reString = sb.toString();
		return reString;
	}
	/*类型转换*/
	
	
	/**
     * @param sql lowcase
     * @return
     */
    public static String matchSql(String sql){
        Matcher matcher = null;
        //SELECT 列名称 FROM 表名称
        //SELECT * FROM 表名称
        if( sql.startsWith("select") ){
            matcher = Pattern.compile("select\\s.+from\\s(.+)where\\s(.*)").matcher(sql);
            if(matcher.find()){
                return matcher.group(1);
            }
        }
        //INSERT INTO 表名称 VALUES (值1, 值2,....)
        //INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)
        if( sql.startsWith("insert") ){
            matcher = Pattern.compile("insert\\sinto\\s(.+)\\(.*\\)\\s.*").matcher(sql);
            if(matcher.find()){
                return matcher.group(1);
            }
        }
        //UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
        if( sql.startsWith("update") ){
            matcher = Pattern.compile("update\\s(.+)set\\s.*").matcher(sql);
            if(matcher.find()){
                return matcher.group(1);
            }
        }
        //DELETE FROM 表名称 WHERE 列名称 = 值
        if( sql.startsWith("delete") ){
            matcher = Pattern.compile("delete\\sfrom\\s(.+)where\\s(.*)").matcher(sql);
            if(matcher.find()){
                return matcher.group(1);
            }
        }
        return null;
    }

	public boolean isChildstr(String text, String cText){
		if(text==null) return false;
		if(cText==null) return false;
		if(text.equals(leftStr(cText, text.length()))){
			return true;
		}
		return false;
	}
	
	public static String[] distinct(String[] arr) {
        if(arr==null || arr.length==0) {
            return arr;
        }
        HashSet<String> set = new HashSet<String>();
        for (String str : arr) {
            set.add(str);
        }
        return set.toArray(new String[0]);
    }
	
	public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isNotEmpty(final CharSequence str) {
        return !isEmpty(str);
    }

    public static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (Character.isWhitespace(cs.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }

    public static boolean isNotBlank(final CharSequence cs) {
        return !isBlank(cs);
    }

    public static boolean equals(String str1, String str2) {
        return str1 == null?str2 == null:str1.equals(str2);
    }

    public static boolean equalsIgnoreCase(String str1, String str2) {
        return str1 == null?str2 == null:str1.equalsIgnoreCase(str2);
    }

    public static boolean contains(String[] arr, String searchStr) {
        if (arr == null || searchStr == null) {
            return false;
        }
        for(String str : arr) {
            if(searchStr.equals(str)){
                return true;
            }
        }
        return false;
    }

    /**
     * StringUtils.capitalize(null)  = null
     * StringUtils.capitalize("")    = ""
     * StringUtils.capitalize("cat") = "Cat"
     * StringUtils.capitalize("cAt") = "CAt"
     * StringUtils.capitalize("'cat'") = "'cat'"
     *
     * @param str
     * @return
     */
    public static String capitalize(final String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return str;
        }

        final char firstChar = str.charAt(0);
        final char newChar = Character.toTitleCase(firstChar);
        if (firstChar == newChar) {
            // already capitalized
            return str;
        }

        char[] newChars = new char[strLen];
        newChars[0] = newChar;
        str.getChars(1,strLen, newChars, 1);
        return String.valueOf(newChars);
    }
    
    public static String getPinyin(String text) throws Exception{
    	Converter converter= new PinyinConverter();
    	String s=converter.getPinyin(text);
    	converter=null;
    	return s;
    }
    
    public static String getPinyinAbbreviation(String text) throws Exception{
    	Converter converter= new PinyinConverter();
    	String s=converter.getPinyinAbbreviation(text);
    	converter=null;
    	return s;
    }

    public static ArrayList<String> castToArrayStr(String text, String dot){
    	if(text==null) return null;
    	text=text.trim();
    	if("".equals(text)) return null;
    	ArrayList<String> list=new ArrayList<String>();
    	if(text.indexOf(dot)<0) list.add(text);
    	else {
    		String[] slist=text.split(dot);
    		int len=slist.length;
    		for(int i=0; i<len; i++){
    			list.add(slist[i]);
			}
		}
		return list;
	}

	public static String getVarKey(String value){
    	if(value==null) return null;
    	if(value.indexOf("#{")==0){
    		value=value.trim();
    		return value.substring(2, value.length()-1);
		}
    	return null;
	}

	public static String[] castToAString(ArrayList<String> list){
    	if(list==null) return null;
    	return list.toArray(new String[list.size()]);
	}

	public static String getJPAName(String id){
		if(id.indexOf("_")<0){
			return id.toLowerCase();
		} else {
			String jid="";
			String[] list=(id+"_").split("_");
			int len=list.length;
			for(int i=0; i<len; i++){
				String k=list[i];
				if(k!=""){
					if(i==0){
						jid=k.toLowerCase();
					} else {
						jid=jid+leftStr(k,1).toUpperCase()+rightStr(k, k.length()-1).toLowerCase();
					}
				}
			}
			if("".equals(jid)){
				jid=id;
			}
			return jid;
		}
	}

	public static String getJPANameTo(String id){
    	String sid="";
    	if(id.indexOf("_")>0){
    		return id;
		}
    	int len=id.length();
    	for(int i=0; i<len; i++){
    		String sch=id.substring(i, i+1).toUpperCase();
    		char ch=id.charAt(i);
			if(Character.isUpperCase(ch)){
				if(i+1<len && !Character.isUpperCase(id.charAt(i+1))){
					sid=sid+"_";
				}
			}
			sid=sid+sch;
		}
    	return sid;
	}

}
